import React, { useEffect } from 'react';
import { Table, Button, message, Popconfirm } from 'antd';
import { useDispatch, useSelector } from 'dva';
import { AsyncModal, FormPannel } from 'src/components/index';

export const BOOK_STATUS = {
  NORMAL: 0, // 正常
  LOANED: 1, // 借出
  DISABLE: 2, // 禁用
};

export const BOOK_STATUS_MAP = {
  0: '正常',
  1: '借出',
  2: '禁用',
};

export default function Category() {
  const { list } = useSelector((state: any): any => {
    return state.present.category;
  });
  const dispatch = useDispatch();

  const getList = async () => {
    try {
      await dispatch({ type: 'category/list' });
    } catch (error) {
      console.log(error);
    }
  };

  const handleEdit = async (row: any) => {
    const { result } = await AsyncModal.show({
      title: '编辑',
      content: ({ onFinish, destory }) => (
        <FormPannel
          columns={formColumns}
          onFinish={onFinish}
          showInModal
          hiddenResetBtn
          layout={{ column: 1 }}
          itemLayout={{ labelCol: { span: 4 }, wrapperCol: { span: 20 } }}
          addonButton={() => (
            <Button onClick={destory} style={{ marginRight: '10px' }}>
              取消
            </Button>
          )}
          initialValues={row}
        />
      ),
      footer: null,
      request: async (values: any) =>
        await dispatch({ type: 'category/edit', payload: { ...values, id: row.id } }),
    });
    if (!result) return;
    message.success('添加成功');
    getList();
  };

  // 删除
  const handleDelete = async (book: any) => {
    // 解除关联
    console.log(book);
    try {
      await dispatch({ type: 'category/delete', payload: book.id });
      message.success('删除成功');
      getList();
    } catch (error) {
      console.info(error);
    }
  };

  const formColumns = [
    { title: '名称', key: 'name', rules: [{ required: true, message: '请输入' }] },
    { title: '描述', key: 'desc', rules: [{ required: true, message: '请输入' }] },
  ];

  const columns = [
    { title: 'id', dataIndex: 'id' },
    { title: '名称', dataIndex: 'name' },
    { title: '描述', dataIndex: 'desc' },
    {
      title: '操作',
      dataIndex: 'operation',
      render: (_val, row) => {
        return (
          <div>
            <Button size="small" style={{ marginRight: '10px' }} onClick={() => handleEdit(row)}>
              编辑
            </Button>
            <Popconfirm
              title="确认要删除吗？"
              onConfirm={() => handleDelete(row)}
              disabled={row.status === BOOK_STATUS.LOANED}
            >
              <Button
                type="primary"
                danger
                size="small"
                disabled={row.status === BOOK_STATUS.LOANED}
              >
                删除
              </Button>
            </Popconfirm>
          </div>
        );
      },
    },
  ];

  useEffect(() => {
    getList();
  }, []);

  const handleAdd = async () => {
    const { result } = await AsyncModal.show({
      title: '添加',
      content: ({ onFinish, destory }) => (
        <FormPannel
          columns={formColumns}
          onFinish={onFinish}
          showInModal
          hiddenResetBtn
          layout={{ column: 1 }}
          itemLayout={{ labelCol: { span: 4 }, wrapperCol: { span: 20 } }}
          addonButton={() => (
            <Button onClick={destory} style={{ marginRight: '10px' }}>
              取消
            </Button>
          )}
        />
      ),
      footer: null,
      request: async (values: any) => await dispatch({ type: 'category/add', payload: values }),
    });
    if (!result) return;

    message.success('添加成功');
    getList();
  };

  return (
    <div>
      <h1>图书分类</h1>
      <Button type="primary" onClick={handleAdd} style={{ marginBottom: '15px' }}>
        添加
      </Button>
      <Table columns={columns} dataSource={list} />
    </div>
  );
}
